package com.example.field.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;


public class RedisUtils {

    @Autowired
    public RedisTemplate<String,Object> redisTemplate;

    //指定缓存过期时间
    public boolean expire(String key,long time){
        try{
            if(time>0)
            {
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //获取缓存过期时间
    public long getExpire(String key)
    {
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    //判断key是否存在
    public boolean hasKey(String key)
    {
        try{
            return redisTemplate.hasKey(key);
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }




    /**
     * 将指定的键值对存入Redis中，并可选设置过期时间（单位：秒）
     */
    public void set(String key, Object value, long expirationSeconds) throws JsonProcessingException {
        String json = new ObjectMapper().writeValueAsString(value);
        redisTemplate.opsForValue().set(key, json);
        if (expirationSeconds > 0) {
            redisTemplate.expire(key, expirationSeconds, TimeUnit.SECONDS);
        }
    }
    //set的两个参数重载,将指定的键值对存入Redis中，如果不设置过期时间，默认不过期
    public void set(String key, Object value) throws JsonProcessingException {
        String json = new ObjectMapper().writeValueAsString(value);
        redisTemplate.opsForValue().set(key, json);
    }

    /**
     * 根据指定的键获取对应的值
     */
    //get函数(返回json数据)
    public Object get(String key) throws JsonProcessingException {
        if(hasKey(key))
        {
            String valueFromRedis = (String) redisTemplate.opsForValue().get(key);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(valueFromRedis);
            return jsonNode;
        }
        return null;

    }

    // 根据指定的键删除一个或多个对应的值
    public void remove(String... keys) {
        if(keys !=null && keys.length>0)
        {
            for (String key : keys) {
                redisTemplate.delete(key);
            }
        }

    }
}
